package jdly.water.api.config.shiro;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.alibaba.fastjson.JSONObject;

import jdly.water.api.common.service.R;

/**
 * shiro未登录反回状态码
 * 
 * @author xuguoqin
 * @date 2018年5月10日
 * @version 1.0
 */
public class LoginAuthorizationFilter extends FormAuthenticationFilter {

	/**
	 * 这个方法是未登录需要执行的方法
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

		HttpServletResponse httpResponse = (HttpServletResponse) response;
		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {
			// 设置响应头
			httpResponse.setCharacterEncoding("UTF-8");
			httpResponse.setContentType("application/json");
			// 设置返回的数据
			R r = R.ok();
			// 写回给客户端
			PrintWriter out = httpResponse.getWriter();
			out.write(JSONObject.toJSONString(r));
			// 刷新和关闭输出流
			out.flush();
			out.close();
		} else {
			//登录失效，重新登录
			// 设置响应头
			httpResponse.setCharacterEncoding("UTF-8");
			httpResponse.setContentType("application/json");
			// 设置返回的数据
			JSONObject json = new JSONObject();
			json.put("code", "100000");
			json.put("msg", "登录实效，请重新登录！");
			// 写回给客户端
			PrintWriter out = httpResponse.getWriter();
			out.write(JSONObject.toJSONString(json));
			// 刷新和关闭输出流
			out.flush();
			out.close();
		}
		return false;
	}
}
